from flask import g
from flask import redirect
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.image_storage import storage
from info.models import News,Comment, User, Category
from info.utils.common import login_user_data
from info.utils.response_code import RET
from . import user_blue
from flask import render_template, current_app, jsonify


@user_blue.route('/info', methods=['GET','POST'])
@login_user_data
def info():
    user=g.user
    if not user:
        return redirect('/')
    data={
        'user':user.to_dict()
    }
    return render_template('news/user.html',data=data)

@user_blue.route('/base_info',methods=['GET','POST'])
@login_user_data
def base_info():
    #获取参数
    user=g.user

    data = {
        'user': user.to_dict(),
    }
    if request.method=='GET':
        return render_template('news/user_base_info.html',data=data)

    nick_name=request.json.get('nick_name')
    signature=request.json.get('signature')
    gender=request.json.get('gender')

    #校验参数
    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if gender not in['MAN','WOMAN']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    #更改用户信息
    user.nick_name=nick_name
    user.signature=signature
    user.gender=gender

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    session['nick_name']=nick_name
    return jsonify(errno=RET.OK,errmsg='更新成功')



@user_blue.route('/pic_info',methods=['GET','POST'])
@login_user_data
def pic_info():
    user=g.user
    data={
        'user':user.to_dict()
    }
    if request.method=='GET':
        return render_template('news/user_pic_info.html',data=data)

    #获取参数
    #校验
    try:
        avatar_data = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    #上传到千牛云

    try:
        avatar_name = storage(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='第三方错误')

    #存储到数据库
    user.avatar_url=avatar_name
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    #返回模板数据
    return jsonify(errno=RET.OK,errmsg='成功',data={'avatar_url':constants.QINIU_DOMIN_PREFIX+avatar_name})

@user_blue.route('/pass_info', methods=["GET", "POST"])
@login_user_data
def pass_info():
    if request.method == "GET":
        return render_template('news/user_pass_info.html')

    # 1. 获取到传入参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 获取当前登录用户的信息
    user = g.user

    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 更新数据
    user.password = new_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="保存成功")


@user_blue.route('/collection')
@login_user_data
def collection():
    #获取参数
    page=request.args.get('page',1)
    #校验
    try:
        page=int(page)
    except Exception as e:
        current_app.logger.error(e)
        page=1

    #从数据库中读取数据
    user=g.user
    try:
        paginate=user.collection_news.paginate(page,constants.COLLECTION_PER_PAGE)
        db.session.commit()
        page=paginate.page
        pages=paginate.pages
        collection_model=paginate.items
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        page=1
        pages=1
        collection_model=[]

    collection_list=[]
    for collection in collection_model:
        collection_list.append(collection.to_dict())

    data={
        'current_page':page,
        'total_page':pages,
        'collection_list':collection_list,
    }

    return render_template('news/user_collection.html',data=data)



@user_blue.route('/news_release', methods=['GET', 'POST'])
@login_user_data
def news_release():

    # GET请求传递分类数据并渲染模板
    if request.method == 'GET':
        # 查询分类
        category_models = []
        try:
            category_models = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")

        # 模型转字典
        category_list = []
        for category in category_models:
            category_list.append(category.to_dict())

        # 删除第一个元素
        category_list.pop(0)

        data = {
            'category_list': category_list
        }
        return render_template('news/user_news_release.html', data=data)

    # POST请求
    # 一. 获取参数
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    # 二. 校验参数
    # 1. 完整性
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 读取图片
    try:
        image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3. 分类ID(类型, 查询是否已存在)
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        category_model = Category.query.get(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    if not category_model:
        return jsonify(errno=RET.NODATA, errmsg="无分类数据")

    # 三. 逻辑处理
    # 1. 上传图片
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 2. 创建新闻模型
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    # 新闻很多是爬来的. 网址前缀并非统一. 为了读取方便, 我们统一都加上前缀
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id  # 发布新闻的人
    # 1代表待审核状态
    news.status = 1

    # 3. 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 四. 返回数据
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")



@user_blue.route('/user_follow')
@login_user_data
def user_follow():
    #先获取页码参数
    page=request.args.get('p',1)
    try:
        page=int(page)
    except Exception as  e:
        current_app.logger.error(e)
        page=1

    #然后获取user关注的人,total_page,current_page,
    user=g.user
    try:
        users_paginate=user.followed.paginate(page,constants.FOLLOWED_USER_PERMAX,False)
        current_page=users_paginate.page
        total_page=users_paginate.pages
        user_models=users_paginate.items
    except Exception as e:
        current_app.logger.error(e)
        current_page=1
        total_page=1
        user_models=[]

    users=[]
    for user in user_models:
        users.append(user.to_dict())

    data={
        'current_page':current_page,
        'total_page':total_page,
        'users':users
    }

    return render_template('news/user_follow.html',data=data)


@user_blue.route('/user_news_list')
@login_user_data
def user_news_list():
    #拿page参数和user
    page=request.args.get('page',1)
    # 校验参数
    try:
        page=int(page)
    except Exception as e:
        current_app.logger.error(e)
        page=1

    user=g.user
    #根据page,user.id查找新闻模型
    try:
        news_paginate=News.query.filter(News.user_id==user.id).paginate(page,constants.USER_NEWS_LIST_PERMAX,False)
        news_models=news_paginate.items
        current_page=news_paginate.page
        total_page=news_paginate.pages
    except Exception as e:
        news_models=[]
        current_page=1
        total_page=1
    #模型转字典,渲染模板返回
    news_list=[]
    for news in news_models:
        news_list.append(news.to_review_dict())

    data={
        'current_page':current_page,
        'total_page':total_page,
        'news_list':news_list
    }

    return render_template('news/user_news_list.html',data=data)